package com.xm.share.web.intercepter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.xm.share.common.config.Constants;
import com.xm.share.model.UserInfo;

public class AdminIntercepter implements HandlerInterceptor {

	private static final Logger LOGGER = LoggerFactory.getLogger(AdminIntercepter.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		LOGGER.debug("检查是否是后台管理用户");
		UserInfo userInfo = (UserInfo) request.getSession().getAttribute(Constants.CURRENT_USER);
		if (userInfo == null) {
			response.sendRedirect(request.getContextPath() + "/login");
		} else {
			String authority = userInfo.getGrantedAuthority();
			if(!"administrator".equals(authority)){
				String script = "<script>alert('没有管理员权限')</script>";
				response.getWriter().write(script);
			}
		}
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
	}

}